package com.mission.schedule.appwidget;

import android.app.ActivityManager;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.mission.schedule.cutimage.Log;
import com.mission.schedule.service.ClockService;

import java.util.List;

/**
 * Created by liwei on 2016/11/10.
 */

public class AppwidgetAlarmService extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getStringExtra("msg").equals("update")){
            Log.e("TAG","AppwidgetAlarmService----update");
            if (isServiceRunning(context, "com.mission.schedule.service.ClockService") == false ){
                Intent intentclock = new Intent(context, ClockService.class);
                intentclock.setAction("com.mission.schedule.service.ClockService");
                intentclock.setPackage(context.getPackageName());
                intentclock.putExtra("WriteAlarmClockwrite", "0");
                context.startService(intentclock);
            }
            Intent intenta = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            Bundle extras = new Bundle();
            intenta.putExtras(extras);
            context.sendBroadcast(intenta);
        }
    }


    /**
     * 用来判断服务是否运行.
     *
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
//            Log.e("TAG", serviceList.get(i).service.getClassName());
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
}
